<?php

namespace App\Console\Commands;

use App\Model\Union;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class pkSendGift extends Command
{
    /**
     * pk排位赛执行发放奖励
     * 参数 --data='{json}'
     */
    protected $signature = 'pkSendGift {--data=}';

    /**
     * 
     * The console command description.
     *
     * @var string
     */
    protected $description = 'pk排位赛奖励发放系统';
    protected $connection = 'api'; 
    protected $activityConn = 'activity';//活动数据库

    protected $union_table = 'union'; //公会model
    protected $union_room_table = 'union_room';//公会房间
    protected $finance_union_room_stream_table = 'finance_union_room_stream';//公会房间流水
    protected $gift_steam_table = 'gift_stream';//送礼记录表
    protected $user_table = 'user';//用户表
    protected $qx_love_user_bridge_table = 'qxlove_user_bridge';//七夕盖楼表
    protected $giftstar_config_table = 'giftstar_config';//周星配置

    protected $log = 'union_pk';//pk日志
    protected $errorLog = 'error_union_pk';//pk错误日志
    

    
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct(); 
    }

    /**
     *
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $data = json_decode($this->option('data'),true);
        if(empty($data))
        {
            die;
        }
        //每日冠军亚军发送3000,1000钻石
        $firstUnid = $data['firstUnionId']; //冠军公会id
        $secondUnionId = $data['secondUnionId']; //亚军公会id
        try{
            DB::beginTransaction();
            /**
             * ==============冠军,亚军钻石发放==开始==========
             */
            // if(!empty($firstUnid) && !empty($secondUnionId))
            // {
            //     //查询冠军公会信息
            //     $unids = [$firstUnid,$secondUnionId];
            //     $uninonInofs = DB::connection($this->connection)->table($this->union_table)->whereIn('uuid',$unids)->get();
            //     $uninonInofs = objToArray($uninonInofs);
            //     if(!empty($uninonInofs))
            //     {
            //         foreach($uninonInofs as $k=>$v)
            //         {
            //             if($v['uuid'] == $firstUnid && $v['uuid'] == $secondUnionId)
            //             {
            //                 $diamon_value = 4000;
            //                 $msg = "恭喜您的公会在".Carbon::yesterday()->toDateString().'日PK活动中获取冠、亚军,系统已经为您下发'.$diamon_value.'个钻石,请注意查收.';
            //             }else if($v['uuid'] == $firstUnid){
            //                 $diamon_value = 3000;
            //                 $msg = "恭喜您的公会在".Carbon::yesterday()->toDateString().'日PK活动中获取冠军,系统已经为您下发'.$diamon_value.'个钻石,请注意查收.';
            //             }else{
            //                 $diamon_value = 1000;
            //                 $msg = "恭喜您的公会在".Carbon::yesterday()->toDateString().'日PK活动中获取亚军,系统已经为您下发'.$diamon_value.'个钻石,请注意查收.';
            //             }
            //             //给对应公会长发钻石
            //             $requestData = [
            //                 'user_id' => $v['un_user_id'],
            //                 'type' => 4,//4.后台钻石-加减
            //                 'amount' => $diamon_value,
            //                 'description' => 'PK赠送钻石'.$diamon_value.'钻',
            //             ];
            //             $res = curl_request(getKkaudioApiUrl() . '/activity/increase', $requestData, 'urlencoded', 'POST');
            //             //系统通知
            //             $requestData = [
            //                 'user_id' => $v['un_user_id'],
            //                 'msg' => $msg,
            //             ];
            //             //发送系统消息通知用户
            //             curl_request(getKkaudioApiUrl(). '/msg/text', $requestData);
            //             write_log($this->log,'INFO PK发放'.$diamon_value.'钻用户:'.$v['un_user_id'].'状态',$res);    
            //         }
            //     }
            // }
            /**
             * ==============冠军,亚军钻石发放==结束==========
             */

             /**
             * ==============房间流水==开始==========
             */
            //根据当日开始时间段和结束时间段,主播,房间情况同步到公会房间流水表中
            $start_time = strtotime($data['start_time']);//pk开始时间段
            $end_time =  strtotime($data['end_time']);//pk结束时间段
            $injoinUser = $data['users'];//参加活动的房间+主播
            
            //处理更新房间流水表
            foreach($injoinUser as $value){
                
                //查询送礼记录表数据
                $user_ids = DB::connection($this->connection)->table($this->user_table)->whereIn('uuid',$value['uuids'])->get(['user_id']);
                $user_ids = objToArray($user_ids);
                $userids = array_column($user_ids,'user_id');
                $gift_steam = DB::connection($this->connection)->table($this->gift_steam_table)
                ->whereIn('user_id',$userids)
                ->whereBetween('change_timestamp',[$start_time,$end_time])
                ->where('room_id',37482)
                ->get();
                $gift_steam = objToArray($gift_steam);
                //同步到对应公会房间里
                if(!empty($gift_steam))
                {
                    foreach($gift_steam as $g){
                        //根据房间id查询公会id
                        $unionInfo = DB::connection($this->connection)->table($this->union_room_table)->where('room_id',$value['roomid'])->first();
                        $unionInfo = objToArray($unionInfo);
                        $log = [
                            'union_id' => $unionInfo['un_id'],
                            'room_id' => $unionInfo['room_id'],
                            'user_id' => $g['user_id'],
                            'from_user_id' => $g['from_user_id'],
                            'data_type' => $g['type'],//类型 1=购买礼物 2=背包礼物 3=宝箱
                            'data_value' => $g['gift_price'],
                            'data_id' => $g['gift_id'],
                            'data_num' => $g['gift_num'],
                            'created_at' => date('Y-m-d H:i:s',$g['change_timestamp']),
                            'data_desc' =>'PK排位结算'
                        ];
                        $insertUnionSteam = DB::connection($this->connection)->table($this->finance_union_room_stream_table)->insertGetId($log);
                        
                        write_log($this->log,'INFO '.$unionInfo['room_id'].'房间PK插入房间公会流水状态',$insertUnionSteam);
                    }
                }
            }
           
            /**
             * ==============房间流水==结束==========
             */
            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            write_log($this->errorLog, "PK房间错误信息", '发送错误文件===>'.$e->getFile().PHP_EOL."发生错误行===>".$e->getLine().PHP_EOL.'发生错误信息====>'.$e->getMessage());
        }
    }
    
}
